package com.example.intmysql.Contrller;


import com.example.intmysql.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class UserContrller {
    //用于访问数据库的组件
    @Autowired
    JdbcTemplate jdbcTemplate;


    @RequestMapping("user")
    public Object user(){
//        List<Map<String, Object>> list =  jdbcTemplate.queryForList("select * from user");
        User user =  jdbcTemplate.queryForObject("select * from user where id=1 ", new BeanPropertyRowMapper<>(User.class));
        return user;
    }

    @RequestMapping("users")
    public Object users(@RequestParam String name){
        System.out.println(name);
        String sql;
        StringBuffer sbf = new StringBuffer("select *from user");
        if(name != null || name != ""){
            sbf.append("where name like '%"+name+"%'");
        }
        sql = sbf.toString();
        List<User> list =  jdbcTemplate.query(sql,new BeanPropertyRowMapper(User.class));
//        User u = list.get(0);
        return list;
    }

    @RequestMapping("add")
    public Object add(){
        String sql = "INSERT INTO user(id,name)  VALUES (null, ?) ";
        int succ = jdbcTemplate.update(sql,"李四");
        return succ;
    }

    @RequestMapping("del/{id}")
    public Object del(@PathVariable Integer id){
        String sql = "DELETE from user where id = ? ";
        int succ = jdbcTemplate.update(sql,12);
        return succ;
    }


}
